package com.xiaoyilin;

import com.xiaoyilin.proto.MessageServiceGrpc;
import com.xiaoyilin.proto.Request;
import com.xiaoyilin.proto.Response;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;

/**
 * @author Administrator
 */
public class GrpcClient {

    /**
     * 阻塞/同步 的stub(存根)
     */
    private final MessageServiceGrpc.MessageServiceBlockingStub messageServiceBlockingStub;

    /**
     * 非阻塞/异步 的stub
     */
    private final MessageServiceGrpc.MessageServiceStub messageServiceStub;

    /**
     * todo
     */
    private final MessageServiceGrpc.MessageServiceFutureStub messageServiceFutureStub;

    public GrpcClient(String host, int port) {
        this(ManagedChannelBuilder.forAddress(host, port)
                .usePlaintext()
                .build());
    }

    private GrpcClient(ManagedChannel channel) {
        this.messageServiceBlockingStub = MessageServiceGrpc.newBlockingStub(channel);
        this.messageServiceStub = MessageServiceGrpc.newStub(channel);
        this.messageServiceFutureStub = MessageServiceGrpc.newFutureStub(channel);
    }

    /**
     * @param terminalId
     */
    public void invoke(String terminalId) {
        Request request = Request.newBuilder().setTerminalId(terminalId).build();
        Response response = null;
        try {
            response = messageServiceBlockingStub.controlTerminal(request);
        } catch (StatusRuntimeException e) {
            System.out.println(String.format("rpc failed:%s", e.getStatus()));
        }
        System.out.println("Greeting: " + response);
    }


}
